# search_page.py
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

class SearchPage:
    def __init__(self, driver):
        self.driver = driver
        self.url = 'http://example.com/search'
        self.search_input_locator = (By.ID, 'search-input')  # 搜索输入框定位器
        self.search_button_locator = (By.ID, 'search-button')  # 搜索按钮定位器
        self.search_results_locator = (By.ID, 'search-results')  # 搜索结果列表定位器
        self.result_count_locator = (By.ID, 'result-count')  # 结果数量定位器
        self.clear_search_button_locator = (By.ID, 'clear-search-button')  # 清除搜索按钮定位器
        self.first_result_locator = (By.CSS_SELECTOR, '#search-results .result:first-child')  # 第一个结果定位器
        self.last_result_locator = (By.CSS_SELECTOR, '#search-results .result:last-child')  # 最后一个结果定位器
        self.no_results_message_locator = (By.ID, 'no-results-message')  # 无结果消息定位器

    # 导航到搜索页面
    def navigate(self):
        self.driver.get(self.url)

    # 输入搜索关键词
    def enter_search_term(self, term):
        self.driver.find_element(*self.search_input_locator).send_keys(term)

    # 点击搜索按钮
    def click_search_button(self):
        self.driver.find_element(*self.search_button_locator).click()

    # 获取搜索结果列表
    def get_search_results(self):
        return self.driver.find_elements(*self.search_results_locator)

    # 获取结果数量
    def get_result_count(self):
        return int(self.driver.find_element(*self.result_count_locator).text.split()[0])

    # 清除搜索
    def clear_search(self):
        self.driver.find_element(*self.clear_search_button_locator).click()

    # 获取第一个搜索结果
    def get_first_result(self):
        return self.driver.find_element(*self.first_result_locator).text

    # 获取最后一个搜索结果
    def get_last_result(self):
        return self.driver.find_element(*self.last_result_locator).text

    # 获取无结果消息
    def get_no_results_message(self):
        return self.driver.find_element(*self.no_results_message_locator).text

    # 等待搜索结果加载
    def wait_for_search_results(self):
        WebDriverWait(self.driver, 10).until(
            EC.presence_of_element_located(self.search_results_locator)
        )

    # 等待无结果消息出现
    def wait_for_no_results_message(self):
        WebDriverWait(self.driver, 10).until(
            EC.presence_of_element_located(self.no_results_message_locator)
        )